<?php

class comments extends Module {
	
	public function __construct () {
		parent::__construct (__CLASS__);
		
		$this->extend ('__custom_comments');
	}
	
	public function getcomments ($sTypeName = false, $objectId = false) {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$oCommentType = $typesController->getTypeByName ('comment');
		
		$sel = new Selection;
		$sel->addType ($oCommentType);
		$sel->setOrder ('pubdate');
		
		if ($sTypeName === false && getRequest ('param0') != '') {
			$sTypeName = getRequest ('param0');
		}
		if ($objectId === false && getRequest ('param1', 'int') != 0) {
			$objectId = getRequest ('param1', 'int');
		}
		
		if ($sTypeName !== false) {
			if ($oType = $typesController->getTypeByName ($sTypeName)) {
				$sel->addFilter ('type_id', $oType->getId ());
			}
		}
		if ($objectId !== false) {
			$sel->addFilter ('object_id', $objectId);
		}
		
		$aObjects = $objectsController->getObjectsList ($sel->getList ());
		
		$aRelatedList = array ();
		$aNormalList = array ();
		
		foreach ($aObjects as $object) {
			if (userGroup (ExplaySession::getUser()->getValue ('group')) != 'guest' && ExplaySession::getUserId () != $object->getValue ('owner_id')) {
				$object->setAttribute ('allow-vote', '1');
			} else {
				$object->setAttribute ('allow-vote', '0');
			}
			$aRelatedList[$object->getValue('rel_id')][] = $object;
		}
		
		if (isset ($aRelatedList[0])) {
			$this->detectLevel ($aRelatedList[0], 0, $aRelatedList, $aNormalList);
		}
		
		$response = new ModuleResponse;
		$response->setTemplate (getRequest('reload', 'bool') ? 'comments/showComments' : 'comments/defaultList');
		$response->setAttribute ('type-name', $sTypeName);
		$response->setAttribute ('object-id', $objectId);
		foreach ($aNormalList as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public function get (Type $oType, $objectId, $sTemplate = 'comments/defaultList', $limitStart = false, $limitEnd = false) {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$oCommentType = $typesController->getTypeByName ('comment');
		
		$sel = new Selection;
		$sel->addType ($oCommentType);
		$sel->setOrder ('pubdate');
		$sel->addFilter ('type_id', $oType->getId ());
		$sel->addFilter ('object_id', $objectId);
		
		if ($limitStart !== false && $limitEnd !== false) {
			$sel->addLimit ((int) $limitStart, (int) $limitEnd);
		}
		
		$aObjects = $objectsController->getObjectsList ($sel->getList ());
		
		$aRelatedList = array ();
		$aNormalList = array ();
		
		foreach ($aObjects as $object) {
			if ($object->getValue ('deleted') == 1) {
				$object->setValue ('text', '');
			}
			
			if (userGroup (ExplaySession::getUser()->getValue ('group')) != 'guest' && ExplaySession::getUserId () != $object->getValue ('owner_id')) {
				$object->setAttribute ('allow-vote', '1');
			} else {
				$object->setAttribute ('allow-vote', '0');
			}
			$aRelatedList[$object->getValue('rel_id')][] = $object;
		}
		
		if (isset ($aRelatedList[0])) {
			$this->detectLevel ($aRelatedList[0], 0, $aRelatedList, $aNormalList);
		}
		
		$response = new ModuleResponse;
		$response->setTemplate ($sTemplate);
		$response->setAttribute ('type-name', $oType->getName ());
		$response->setAttribute ('object-id', $objectId);
		foreach ($aNormalList as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public function ajax_delete () {
		$id = getRequest ('param0', 'int');
		
		if ($oComment = ObjectsController::getInstance ()->getObject (TypesController::getInstance()->getTypeByName ('comment'), $id)) {
			$oComment->setValue ('deleted', 1);
			$oComment->save ();
			$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
		}

		$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
	}
	
	public function ajax_vote () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$id = getRequest ('param0', 'int');
		$mark = getRequest ('param1', 'int');
		
		$oCommentType = $typesController->getTypeByName ('comment');
				
		if (!$oComment = $objectsController->getObject ($oCommentType, $id)) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVoteType = $typesController->getTypeByName ('vote');
		
		$sel = new Selection;
		$sel->addType ($oVoteType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addFilter ('object_id', $id);
		$sel->addFilter ('type_id', $oCommentType->getId ());
		
		if ($sel->getTotalCount () > 0) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVote = new Object ($oVoteType);
		$oVote->setValues (array (
			'type_id' => $oCommentType->getId (),
			'object_id' => $id,
			'user_id' => ExplaySession::getUserId (),
			'mark' => $mark == 1 ? '1' : '0'
		));
		$oVote->createNew ();
		
		$rating = $oComment->getValue ('rating');
		$rating = $mark == 1 ? ++$rating : --$rating;
		$oComment->setValue ('rating', $rating);
		$oComment->save ();
		
		$this->flush ((string) new Array2XML ('data', array ('result' => '1', 'rating' => $rating)), 'text/xml');
	}
	
	/**
	 * Возвращает список объектов комментариев
	 * @param array $aTypes массив экземпляров класса Type
	 * @param integer $objectId id объекта (необязательно)
	 * @param integer $ownerId id автора (необязательно)
	 * @param integer $limitStart необязательно
	 * @param integer $limitEnd необязательно 
	 * @param boolean $ascSort порядок сортировки, по-умолчанию true - прямой
	 * @return array
	 */
	private static function getObjectsList (array $aTypes = array (), $objectId = false, $ownerId = false, $limitStart = false, $limitEnd = false, $ascSort = true) {
		$objectsController = ObjectsController::getInstance ();
		$oCommentType = TypesController::getInstance()->getTypeByName ('comment');
		
		$sel = new Selection;
		
		$aTypesIds = array ();
		
		foreach ($aTypes as $oType) {
			if ($oType instanceof Type) {
				$aTypesIds[] = $oType->getId ();
			}
		}
		
		$sel->addFilterIN ('type_id', $aTypesIds);
		
		if ($objectId) {
			$sel->addFilter ('object_id', $objectId);
		}
		
		if ($ownerId) {
			$sel->addFilter ('owner_id', $ownerId);
		}
		
		if ($limitStart && $limitEnd) {
			$sel->addLimit ($limitStart, $limitEnd);
		} elseif ($limitEnd) {
			 $sel->addLimit ($limitEnd);
		}
		
		$sel->setOrder('id', $ascSort);
		
		$list = $sel->getList ();
		
		$aResult = array ();
		
		foreach ($list as $item) {
			$aResult[] = $objectsController->getObject ($oCommentType, $item[0]);
		}
		
		return $aResult;
	}
	
	private function detectLevel (array &$list, $level, &$aRelatedList, &$aNormalList) {
		foreach ($list as $oComment) {
			$oComment->setAttribute ('comment-level', $level);
			$aNormalList[] = $oComment;
			if (isset ($aRelatedList[$oComment->getId()])) {
				$this->detectLevel ($aRelatedList[$oComment->getId()], $level+1, $aRelatedList, $aNormalList);
			}
		}
	}
	
}